const {nowTime,emptyData,fileterTime} = require("../utils/misc")
const ObjectId = require('mongodb').ObjectId
const router = require('koa-router')();
const mongo = require('../compents/mongo')

router.prefix('/opalog')


router.get('/list', async ctx => {
    let { page,startTime,endTime,name } = ctx.query
    let where={name},fileterData={}
    // 判断是否传值 未传值直接删除对象
    name?"":delete where.name
    let res = await mongo.find('opalog', {where,limit:10000})
    startTime?(endTime?fileterData=fileterTime(res,{startTime,endTime:3000-03-6,page}):""):""
    let total = res.length
    if(JSON.stringify(fileterData)!="{}"){
        res=fileterData.arr
        total=fileterData.total
    }
    if (res) {
        ctx.body = { data: res, code: 20000, total, message: "数据请求成功" }
    } else {
        ctx.body = {data:res, code: 50001, message: "数据请求失败" }
    }
})

router.post('/save', async ctx => {
    let stuData = ctx.request.body
    stuData= emptyData(stuData,["name","ip","log"])
    const res = await mongo.insertOne('opalog', { ...stuData,date:nowTime()})
    if (res.insertedId) {
        ctx.body = { data: res, code: 20000, message: "数据插入成功" };
    } else {
        ctx.body = { data: res, code: 50002, message: "数据插入失败" };
    }
})

// 修改数据库
router.post('/change', async ctx => {
    const { _id } = ctx.request.body
    const update = ctx.request.body
    delete update._id
    const res = await mongo.updateOne('opalog', { where: { _id: ObjectId(_id) }, update })
    if (res.modifiedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据修改成功" };
    } else {
        ctx.body = { data: res, code: 50004, message: "数据修改失败" };
    }
})

// 删除数据
// 删除单挑数据
router.get('/delOne', async ctx => {
    const { _id } = ctx.query
    const res = await mongo.deleteOne('opalog', { _id: ObjectId(_id) })
    if (res.deletedCount > 0) {
        ctx.body = { data: res, code: 20000, message: "数据删除成功" };
    } else {
        ctx.body = { data: res, code: 50005, message: "数据删除失败" };
    }
})
module.exports = router 